import { LayerRange, SampledInfo, SampledResult, SampleParameterValues, SampleStepInfo, WhereSqlParams } from "@/pages/auditSampling/typing";
import { consts } from "@/pages/auditSampling/consts";
import { getIniSampledResult, getSampleSizeAndAmount, getTextFieldsValues, getToBeTestWhereSql } from "../NonStatSampleService";
import { formatNumber } from "devextreme/localization";
import { nanoid10 } from "@/utils";
import getApiData from "@/services/cpasRequest";
import { getRealTableName } from "../../service";
import { getSampleOverallWhereSQL } from "../../samplingProjectOverallService";
import { msgError } from "@/utils/msg";

/**
 * 计算范围值
 * @param layerRangesDecludeLastItem_1   newLayerRanges 不包含最后一行的 
 * @param sampleStepInfo 
 * @param sampleParameterValues 
 * @param lastItem_1 
 */
export function calcRangeValues(layerRangesDecludeLastItem_1: LayerRange[],
    sampleStepInfo: SampleStepInfo, lastItem_1?: LayerRange//rangValue为-1的最后一行
): void {
    const { projectOverallProps } = sampleStepInfo;

    const sumFieldsArray: string[] = projectOverallProps?.curSampleTable?.sampleNumFieldsArray || []
    // const onlyOneAndIsZero = false;
    layerRangesDecludeLastItem_1.forEach((item, index, items) => {
        let sql = "  /*layerRangeWhereSql:*/  and (";
        if (index == 0) {
            const rangeText = item.rangeValue || 0;//` ${formatNumber(item.rangeValue || 0, consts.numberFormat)}`;

            item.rangeText = `< ${rangeText}`
            sql += sumFieldsArray.map(fieldName => 
                ` ( abs(ISNULL([${fieldName}],0)) > 0 and abs(ISNULL([${fieldName}],0)) <= ${item.rangeValue} )`).join(' or ')

        }
        else {
            const previousItem = items[index - 1];
            item.rangeText = `${previousItem.rangeValue || 0} ` + `－${item.rangeValue || 0}`

            sql += sumFieldsArray.map(fieldName =>
                ` ( abs(ISNULL([${fieldName}],0)) > ${previousItem.rangeValue} and abs(ISNULL([${fieldName}],0)) <= ${item.rangeValue} )`
            ).join(' or ')
        }
        sql += ` )`;
        item.rangeWhereSql = sql;
    })

    //增加最后一项 rangeValue=-1
    if (layerRangesDecludeLastItem_1.length > 0 /* && !onlyOneAndIsZero */) {
        const lastItem = layerRangesDecludeLastItem_1[layerRangesDecludeLastItem_1.length - 1]
        let sql = " /*layerRangeWhereSql:*/  and (";
        sql += sumFieldsArray.map(fieldName =>
            ` abs(ISNULL([${fieldName}],0)) >= ${lastItem.rangeValue} `
        ).join(' or ')
        sql += ` )`;

        layerRangesDecludeLastItem_1.push({
            ...lastItem_1,
            guid: nanoid10(),
            orderIndex: layerRangesDecludeLastItem_1.length + 1,
            rangeValue: -1,
            rangeText: `>= ${lastItem.rangeValue || 0}`,
            needSampleSize: lastItem_1?.needSampleSize,
            rangeWhereSql: sql,
        })
    }
}
/**
 * 计算未抽样个数
 * @param layerRangesDecludeLastItem_1 不包含最后一行的 
 * @param sampleStepInfo 
 */
export async function calcUnSampleSize(layerRangesDecludeLastItem_1: LayerRange[],
    sampleStepInfo: SampleStepInfo,
    sampleParameterValues: SampleParameterValues,
    lastItem_1?: LayerRange//rangValue为-1的最后一行
) {
    // const { projectOverallProps } = sampleStepInfo;


    // const sumFieldsArray: string[] = projectOverallProps?.curSampleTable?.sampleNumFieldsArray || []

    //lastItem_1.rangValue为-1的最后一行
    calcRangeValues(layerRangesDecludeLastItem_1, sampleStepInfo, lastItem_1)
    //B.待抽样的测试总体(扣除特定项目后)	 SQL
    const toBeTestWhereSql = getToBeTestWhereSql(sampleParameterValues as any);

    layerRangesDecludeLastItem_1.forEach((item, index) => item.orderIndex = index + 1)
    //未抽样个数

    //  const fixedWhereSql = `${sampleWhereSQL}  ${toBeTestWhereSql}`

    for (let i = 0; i < layerRangesDecludeLastItem_1.length; i++) {
        const whereSql = toBeTestWhereSql + layerRangesDecludeLastItem_1[i].rangeWhereSql;
        const sampleSizeAndAmount = await getSampleSizeAndAmount(sampleStepInfo, whereSql);

        layerRangesDecludeLastItem_1[i].unSampleSize = sampleSizeAndAmount.sampleSize;
    }
}

/**
 * 执行分层抽样
 * @param newLayerRanges 
 * @param sampleStepInfo 
 * @param sampleParameterValues 
 */

export async function getLayerSampleList(
    sampleStepInfo: SampleStepInfo, sampleParameterValues: SampleParameterValues): Promise<SampledResult> {
    const layerSampleParams = sampleParameterValues.layerSampleParams || {}
    const layerRanges: LayerRange[] = layerSampleParams.layerRanges || [];
    const curSampleTable = sampleStepInfo.projectOverallProps?.curSampleTable;
    const sampleTextFieldsArray = curSampleTable?.sampleTextFieldsArray || [];
    const sampleNumFieldsArray = curSampleTable?.sampleNumFieldsArray || [];

    const allSampledResult = getIniSampledResult();
    const allSampledList: SampledInfo[] = [];
    const sampleWhereSQL = getSampleOverallWhereSQL(sampleStepInfo.projectOverallProps?.curWhereSqlParams as WhereSqlParams)
    const toBeTestWhereSql = getToBeTestWhereSql(sampleParameterValues);

    //  const sortFields= curSampleTable?.sortFields

    const lastItem_1 = layerRanges.find(item => item.rangeValue == -1);//rangValue为-1的最后一行
    const newLayerRanges = [...layerRanges.filter(item => item != lastItem_1)];

    for (let i = 0; i < layerRanges.length; i++) {
        const element = layerRanges[i];
        if (!element.needSampleSize) {
            msgError(`第 ${i + 1} 行,请输入需要抽样数量!`)
            return allSampledResult;
        }
    }
    calcRangeValues(newLayerRanges, sampleStepInfo, lastItem_1)
    for (const layerRange of layerRanges) {
        const tableInfoList = sampleNumFieldsArray.map(fieldName => {
            const tableName = getRealTableName(sampleStepInfo.projectOverallProps?.curSampleTable?.tableName || ''
                , { data_id: sampleStepInfo.projectOverallProps?.curDataId || '' });
            const rangeWhereSql = layerRange.rangeWhereSql;
            const whereSql = ` ${sampleWhereSQL} ${toBeTestWhereSql} ${rangeWhereSql}`

            return { tableName, whereSql, amountField: fieldName }
        })

        let sortType = consts.amountRandom;
        if (layerSampleParams.extractType == consts.amountBigToSmall) {
            sortType = consts.desc
        } else if (layerSampleParams.extractType == consts.amountSmallToBig) {
            sortType = consts.asc
        }
        //{sortType,fields,tableInfoList:[{tableName,whereSql,amountField}]}
        const retData = await getApiData('sample.getLayerSampleList', {
            dbname: sampleStepInfo.projectOverallProps?.curWhereSqlParams?.dbname,
            sortType: sortType,//排序方式
            fields: sampleTextFieldsArray.map(fieldName => `[${fieldName}]`).join(','),//需要返回的字段
            tableInfoList: tableInfoList,
            pageIndex: 0,
            pageSize: layerRange.needSampleSize || 0
        })
        if (!retData.ok) msgError(retData.data);

        const sampledList: any[] = retData.data;
        //回写数据赋值
        const sampledResult: SampledResult = {
            sampledList: sampledList,
            sampledSize: sampledList.length,
            sampledAmountSum: sampledList.reduce((pre, cur) => pre + (cur.amountFieldValue || 0), 0) || 0,
            sampleTextFieldValues: sampledList.map(item => getTextFieldsValues(item, sampleTextFieldsArray)),
        };

        layerRange.sampledResult = sampledResult;
        allSampledList.push(...sampledResult.sampledList);
    }

    allSampledResult.sampledList = allSampledList;
    allSampledResult.sampledSize = allSampledList.length;
    allSampledResult.sampledAmountSum = allSampledList.reduce((pre, cur) => pre + (cur.amountFieldValue || 0), 0);
    allSampledResult.sampleTextFieldValues = allSampledResult.sampledList.map(item => getTextFieldsValues(item, sampleTextFieldsArray))
    return allSampledResult;
}